package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.service.CourseCategoryService;
import com.xuecheng.model.dto.CourseCategoryDto;
import com.xuecheng.model.po.CourseCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.xuecheng.base.constant.CourseCategoryConstant.CATEGORY_ROOT;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryDto> getCategoryList() {
        LambdaQueryWrapper<CourseCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(CourseCategory::getId, CATEGORY_ROOT);
        //获取除根节点的所有分类信息
        List<CourseCategory> categoryList = courseCategoryMapper.selectList(wrapper);
        //过滤出一级分类
        List<CourseCategory> oneCate = categoryList.stream()
                .filter(c -> c.getParentid().equals(CATEGORY_ROOT))
                .collect(Collectors.toList());
        //移除一级分类信息，则剩下的分类为二级分类
        categoryList.removeAll(oneCate);
        return oneCate.stream().map(one -> {
            CourseCategoryDto dto = new CourseCategoryDto();
            //映射属性到dto
            BeanUtils.copyProperties(one, dto);
            //对二级分类进行映射
            List<CourseCategory> childrenList = categoryList.stream()
                    .filter(sub -> sub.getParentid().equals(one.getId()))
                    .collect(Collectors.toList());
            dto.setChildrenTreeNodes(childrenList);
            return dto;
        }).collect(Collectors.toList());
    }
}
